package com.lagou.zookeeper;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.CountDownLatch;

/**
 * @program: stage-3-module-2
 * @description:
 * @author: zhangxiaoyang
 * @date: 2020-08-23 22:36
 **/
public class CreateNode implements Watcher {

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static ZooKeeper zooKeeper;
    private String host;
    private int port;


    public CreateNode(String ip, int port) {
        this.host = ip;
        this.port = port;
    }


    public static void init(Watcher watcher) throws IOException {
        zooKeeper = new ZooKeeper(ZkConstant.ZK_SERVER + ":" + ZkConstant.ZK_PORT, 50000, watcher);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            countDownLatch.countDown();
        }

        try {
            createNodeSync();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void createNodeSync() throws UnsupportedEncodingException, KeeperException, InterruptedException {
        if (zooKeeper.exists(ZkConstant.ROOT_NODE, true) == null) {
            zooKeeper.create(ZkConstant.ROOT_NODE, "服务器列表".getBytes("UTF-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        if (zooKeeper.exists(ZkConstant.ROOT_NODE + "/" + (this.host + ":" + this.port), false) == null) {
            String addressNode = zooKeeper.create(ZkConstant.ROOT_NODE + "/" + (this.host + ":" + this.port), "0".getBytes("UTF-8"),
                                                  ZooDefs.Ids.OPEN_ACL_UNSAFE,
                                                  CreateMode.EPHEMERAL);
            System.out.println("创建zk节点成功：" + addressNode);
        }
    }
}
